<template>
  <el-dialog title="选择建筑易损性矩阵" v-model="open" width="800px" @open="initOpen" append-to-body :before-close="close"
    @close="close" :center="false">
    <div class="container">
      <el-link type="primary" :underline="false">当前可选建筑物易损性矩阵数据区域为：{{range}}。</el-link>
      <el-link type="primary" :underline="false">如您需选择更详细的易损性矩阵数据，请到【数据管理-建筑物易损性数据】模块中维护。</el-link>
      <el-form ref="tableForm" :model="form" :rules="rules">
        <el-form-item label=" " prop="tableRadio">
          <el-table :data="data.tableData" :border="true" stripe @row-click="changeRadio">
            <el-table-column v-if="data.isView != 'view'" label="选择" align="center" width="120">
                <template #default="{row}">
                  <div v-for="item in tableRadio">
                    <el-radio-group v-if="row.structureType == item.structureType" v-model="item.isCheck" class="ml-4">
                      <el-radio :label="row.intensity" size="large">{{''}}</el-radio>
                      {{item}}
                    </el-radio-group>
                  </div>
                </template>
            </el-table-column>
            <el-table-column label="结构类型" align="center" prop="structureType">
              <template #default="{row}">
                <span v-if="row.structureType==0">高层建筑</span>
                <span v-else-if="row.structureType==1">钢结构</span>
                <span v-else-if="row.structureType==2">多层钢筋混凝土结构</span>
                <span v-else-if="row.structureType==3">砖混结构</span>
                <span v-else-if="row.structureType==4">砖木结构</span>
                <span v-else-if="row.structureType==5">土结构</span>
                <span v-else-if="row.structureType==6">木结构</span>
                <span v-else-if="row.structureType==7">石结构</span>
                <span v-else-if="row.structureType==8">其他结构</span>
              </template>
            </el-table-column>
            <el-table-column label="设防烈度" align="center" prop="intensity" />
            <el-table-column label="建筑物易损性详情" align="center" prop="">
              <template #default="{row}">
                <el-popover placement="right" :width="600" trigger="click" popper-class="detail-popover"
                  @show="getMatrixChoiceListDetail(row)">
                  <template #reference>
                    <el-link type="primary" :underline="false">详情</el-link>
                  </template>
                  <el-table :data="detailTableData" :border="true" v-loading="detailLoading">
                    <el-table-column prop="destroy" label="破坏程度" align="center">
                      <template #default="{row}">
                        <span v-if="row.destroy==0">基本完好</span>
                        <span v-else-if="row.destroy==1">轻微破坏</span>
                        <span v-else-if="row.destroy==2">中等破坏</span>
                        <span v-else-if="row.destroy==3">严重破坏</span>
                        <span v-else-if="row.destroy==4">损坏</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="name" label="烈度" align="center">
                      <el-table-column prop="six" label="" align="center">
                        <template #header>
                          <span>VI(%)</span><br>
                          <span>0.05g</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="seven" label="" align="center">
                        <template #header>
                          <span>VII(%)</span><br>
                          <span>0.10g</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="eight" label="" align="center">
                        <template #header>
                          <span>VIII(%)</span><br>
                          <span>0.20g</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="nine" label="" align="center">
                        <template #header>
                          <span>IX(%)</span><br>
                          <span>0.40g</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="ten" label="" align="center">
                        <template #header>
                          <span>X(%)</span><br>
                          <span>0.80g</span>
                        </template>
                      </el-table-column>
                    </el-table-column>
                  </el-table>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </div>
    <template #footer v-if="data.isView != 'view'">
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { matrixChoiceListDetail, matrixSave } from '@/api/earthquakeLossesEstimation/earthquakeSetting'

const props = defineProps({
  open: Boolean,
  data: Object
})
const emits = defineEmits(['update:open', 'updateVulnerability'])

const {proxy} = getCurrentInstance()
const route = useRoute()
const { taskId } = route.query

const form = reactive({
  tableRadio: [],
  detailTableData: [],
  detailLoading: true
})
const { tableRadio, detailTableData, detailLoading } = toRefs(form)
const checkList = (rule, value, callback) => {
  let isFull = value.every(item => {
    return item.isCheck != ''
  })
  if (isFull) {
    callback()
  } else {
    callback(new Error("请将结构类型选择完整!"))
  }
}
const tableForm = ref()
const rules = reactive({
  tableRadio: [{ validator: checkList }]
})
const range = computed(() => {
  const {province, city, county} = props.data.parentData
  return province + city + county
})

const initOpen = () => {
  tableRadio.value = props.data.tableData.reduce((prev, cur, curIndex, arr) => {
    let flag = prev.some(item => {
      return item.structureType == cur.structureType
    })
    let isDefaultCheckArr = arr.filter(val => cur.structureType == val.structureType)
    let isDefaultCheck = isDefaultCheckArr.length == 1 ? isDefaultCheckArr[0].intensity : ''
    if (!flag) {
      prev.push({
        structureType: cur.structureType,
        isCheck: isDefaultCheck
      })
    }
    return prev
  }, [])
  form.tableRadio = tableRadio.value
}
const close = () => {
  emits('update:open', false)
  tableForm.value.clearValidate()
}
const getMatrixChoiceListDetail = (row) => {
  detailLoading.value = true
  const { id, province, city, prefecture, structureType, intensity } = row
  matrixChoiceListDetail({ id, province, city, prefecture, structureType, intensity }).then(res => {
    if (res.code == 200) {
      detailTableData.value = res.data
      detailLoading.value = false
    }
  }).catch(err => {
    detailLoading.value = false
  })
}
const changeRadio = (row) => {
  if(props.data.isView == 'view'){
    return 
  }
  tableRadio.value.forEach(item => {
    if(item.structureType == row.structureType){
      item.isCheck = row.intensity
    }
  })
}
// 确定
const submitForm = () => {
  // 保存时校验9组数据是否必填
  tableForm.value.validate(valid => {
    if (valid) {
      let selectData = []
      tableRadio.value.map(radioItem => {
        props.data.tableData.map(item => {
          if (item.structureType == radioItem.structureType && radioItem.isCheck == item.intensity) {
            selectData.push(item)
          }
        })
      })
      selectData = selectData.map(item => {
        return {
          dzIntensity: props.data.parentData.dzIntensity,
          province: item.province,
          city: item.city,
          prefecture: item.prefecture,
          structureType: item.structureType,
          intensity: item.intensity
        }
      })
      matrixSave({ taskId, vulnerability: selectData }).then(res => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('保存成功！')
          close()
          // 更新列表
          emits('updateVulnerability', props.data.index)
        }
      }).catch(err => {})
    }
  })
}
</script>
<style scoped lang="scss">
.container {
  padding: 15px 0 0;
}
</style>
<style lang="scss">
.detail-popover {
  .el-table th.el-table__cell {
    border-bottom: 1px solid #ebeef5 !important;
  }

  .el-table td.el-table__cell {
    border-right: 1px solid #ebeef5 !important;
  }
}

// .el-dialog .el-dialog__footer {
//   text-align: end !important;
//   padding-right: 20px;
// }
</style>